import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/movies'
  }, {
    path: '/movies',
    component: () => import('../views/Movies.vue'),
    meta: { title: '电影', },
    children: [{
      path: '',
      redirect: 'NowPlaying'
    }, {
      path: 'NowPlaying',
      component: () => import('../views/movies/NowPlaying'),
      meta: { title: '正在热映' }
    }, {
      path: 'ComingSoon',
      component: () => import('../views/movies/ComingSoon'),
      meta: { title: '即将上映' }
    }]
  }, {
    path: '/cinema',
    component: () => import('../views/Cinema.vue'),
    meta: { title: '影院' }
  }, {
    path: '/news',
    component: () => import('../views/News.vue'),
    meta: { title: '资讯' }
  }, {
    path: '/personal',
    component: () => import('../views/Personal.vue'),
    meta: {
      title: '我的',
      guardian: true
    }
  }, {
    path: '/detail/:id',
    component: () => import('../views/Detail.vue'),
    meta: {
      title: '详情',
      hideTabBar: true
    }
  }, {
    path: '/city',
    component: () => import('../views/City.vue'),
    meta: {
      title: '城市',
    }
  }, {
    path: '/login',
    component: () => import('../views/personal/Login.vue'),
    meta: { title: '登录' }
  }, {
    path: '/register',
    component: () => import('../views/personal/Register.vue'),
    meta: { title: '注册' }
  }, {
    path: '/edit',
    component: () => import('../views/personal/Edit.vue'),
    meta: { title: '编辑资料' }
  },
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  // 如果当前的路由有meta.guardian,则拦截判断，如果没有则放行
  if (to.matched[0].meta.guardian) {
    // 如果当前本地没有token，跳转登录页面，如果有token放行
    if (!localStorage.getItem('token')) {
      next('/login')
    } else {
      next()
    }
  } else {
    next()
  }
})








const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace;
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch(err => err);
}

export default router
